package com.eqdd.yiqidian.ui.act

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.WriteBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.*
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.kotlin.areaSelect
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.kotlin.timePicker
import com.eqdd.yiqidian.kotlin.utils.TimePickerUtil
import com.eqdd.yiqidian.ui.WriteActivity
import com.eqdd.yiqidian.ui.act.tree.ActTypeTreeActivity
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.utils.HttpUtil
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.PicUtil
import com.eqdd.yiqidian.widget.ChooseAlertView
import com.gamerole.richtextview.RichEditor
import com.kyleduo.switchbutton.SwitchButton
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_act_detail.*
import kotlinx.android.synthetic.main.activity_title.*
import kotlinx.android.synthetic.main.list_item_23.*
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-10-5.
 */
class ActDetailActivity : BaseActivity() {

    private var id: Int = -1
    val dataList = arrayListOf<SlimEditBean>()
    private val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)

    override fun initBinding() {
        setContentView(R.layout.activity_act_detail)
        initTopTitleBar(View.VISIBLE, "活动详情")

    }


    override fun initData() {
        id = 19
        if (id == -1) {
            toast("获取详情失败")
            finish()
            return
        }
        OkGo.post<HttpResult<ActBean>>(HttpConfig.BASE_URL + HttpConfig.ACTIVITY_DETAIL)
                .params("activityId", id)
                .execute(object : DialogCallBack<HttpResult<ActBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<ActBean>>?) {
                        val result = response?.body()
                        result?.items?.let {
                            if (it.creater == user.guid) {
                                layout_my.visibility = View.VISIBLE
                                layout_other.visibility = View.GONE
                                setView(it)
                                iv_right.visibility = View.VISIBLE
                                iv_right.imageResource = R.mipmap.addg
                                val list = arrayListOf<String>("报名情况", "签到情况")
                                popMenu(list, iv_right) { dialog, pos ->
                                    if (pos == 0) {

                                    } else if (pos == 1) {
                                        startActivity<ActSignListActivity>(Config.ID to id)
                                    }
                                }

                            } else {
                                layout_my.visibility = View.GONE
                                layout_other.visibility = View.VISIBLE
                                ImageUtil.setImage(it.activeImg, imageView)
                                tv_title1.text = it.activeTitle
                                tv_type.text = "活动类型：${it.activeType}"
                                tv_classify.text = "活动分类：${it.activeClassify}"
                                tv_object.text = "参会对象：${it.activeObject}"
                                tv_num.text = "参数人数：${it.activeNum.toString()}"
                                tv_scale.text = "活动规模：${it.activeScale}"
                                tv_time.text = "活动时间：${it.activeStartTime}～${it.activeEndTime}"
                                tv_position.text = "活动地点：${it.activeProvince + it.activeCity + it.activeAddress}"
                                richEditor_introduce.html = it.activeDesc
                                richEditor_date.html = it.activeDesc

                            }
                        }
                    }
                })
    }

    private var slimAdapterEx: SlimAdapterEx<SlimEditBean>? = null

    private fun setView(it: ActBean) {

        recylcerView.layoutManager = LinearLayoutManager(this)
        recylcerView.addItemDecoration(DividerLineItemDecoration(this))
        dataList.add(SlimEditEnterBean("活动主题", it.activeTitle, 0, "请输入"))
        dataList.add(SlimEditEnterBean("活动类型", it.activeType, 1, "请输入").setDeal(true))
        dataList.add(SlimEditEnterBean("活动分类", it.activeClassify, 2, "请输入").setDeal(true))
        dataList.add(SlimEditEnterBean("参会对象", it.activeObject, 3, "请输入"))
        dataList.add(SlimEditEnterBean("参会人数", it.activeNum.toString(), 4, "请输入").setInteger(true))
        dataList.add(SlimEditEnterBean("参会规模", it.activeScale, 5, "请输入"))
        dataList.add(SlimEditEnterBean("活动地点", it.activeProvince + it.activeCity + it.activeAddress, 6, "请输入").setDeal(true))
        dataList.add(SlimEditEnterBean("开始时间", it.activeStartTime, 7, "请选择").setDeal(true))
        dataList.add(SlimEditEnterBean("结束时间", it.activeEndTime, 8, "请选择").setDeal(true))
        dataList.add(SlimImageSelectBean("活动封面图", 9, it.activeImg))
        dataList.add(SlimEditHtmlBean("活动描述", it.activeDesc, 10))
        dataList.add(SlimEditHtmlBean("活动日程", it.activeSchedule, 11))
        dataList.add(SlimEditCheckButtonBean("是否收费", "", 12, it.isCharge))
        if (it.isCharge)
            dataList.add(SlimEditEnterBean("费用", it.price, 13, "请输入").setNumber(true))

        slimAdapterEx = SlimAdapterEx.create()
                .register<SlimEditEnterBean>(R.layout.list_item_29, SlimInjector<SlimEditEnterBean> { data, injector ->
                    injector?.text(R.id.tv_left_content, data?.title)
                            ?.text(R.id.tv_right_content, data?.content)
                })
                .register<SlimEditHtmlBean>(R.layout.list_item_177, SlimInjector<SlimEditHtmlBean> { data, injector ->
                    injector?.text(R.id.tv_label, data?.title)
                            ?.with<RichEditor>(R.id.richEditor) {
                                val html = data?.content
                                        ?.replace("<pre>", "")
                                        ?.replace("</pre>", "")
                                it.setPadding(10, 0, 10, 0)
                                it.html = html
                            }
                })
                .register<SlimEditCheckButtonBean>(R.layout.list_item_24, SlimInjector<SlimEditCheckButtonBean> { data, injector ->
                    injector?.text(R.id.tv_left_center_content, data?.title)
                            ?.checked(R.id.sb_end, data?.isCheck ?: false)
                            ?.with<SwitchButton>(R.id.sb_end) {
                                it.setOnCheckedChangeListener { view, isChecked ->
                                    slimAdapterEx?.let {
                                        if (isChecked) {
                                            it.data.add(13, SlimEditEnterBean("费用", null, 12, "请输入").setNumber(true))
                                            it.notifyItemInserted(13)
                                        } else {
                                            it.data.removeAt(13)
                                            it.notifyItemRemoved(13)
                                            upload("isCharge" to false.toString())
                                        }
                                    }

                                }
                            }

                })
                .register<SlimImageSelectBean>(R.layout.layout_image_selected, SlimInjector<SlimImageSelectBean> { data, injector ->
                    injector?.text(R.id.tv_label, data?.title)
                            ?.image(R.id.iv_add, data?.image)
                            ?.clicked(R.id.iv_add) {
                                PicUtil.single(this@ActDetailActivity, true)
                            }
                })
                .attachTo(recylcerView)
                .updateData(dataList as List<*>?) as SlimAdapterEx<SlimEditBean>?

        ItemClickSupport.addTo(recylcerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    slimAdapterEx?.let {
                        val slimEditBean = it.data?.get(position)
                        if (slimEditBean?.isDeal == true) {
                            itemClick(it, position)
                            return@setOnItemClickListener
                        }
                        if (slimEditBean is SlimEditEnterBean) {
                            startActivityForResult<EditTextActivity>(position,
                                    "title" to slimEditBean.title, "tip" to slimEditBean.title,
                                    "content" to slimEditBean.content, "onlyNumber" to slimEditBean.isNumber, "onlyInteger" to slimEditBean.isInteger)
                        } else if (slimEditBean is SlimEditHtmlBean) {
                            startActivityForResult<WriteActivity>(position, Config.TITLE to "活动描述", "isHasTitle" to false,
                                    "content" to slimEditBean.content)
                        }
                    }


                }


    }

    private fun itemClick(slimAdapterEx: SlimAdapterEx<SlimEditBean>, position: Int) {
        when (position) {
            1 -> {
                val list = arrayListOf("论坛", "大会", "线上直播", "点播", "研讨会", "培训", "市场活动", "展览", "聚会", "酒会", "其他")
                bottomDialog(list) {
                    slimAdapterEx.data[2].content = list[it - 1]
                    slimAdapterEx.notifyItemChanged(2)
                    upload("activeType" to list[it - 1])
                }
            }
            2 -> {
                startActivityForResult<ActTypeTreeActivity>(2)
            }
            7 -> {
                val startTime = slimAdapterEx.getDataItem(7).content
                val endTime = slimAdapterEx.getDataItem(8).content
                timePicker(TimePickerUtil.parseData(startTime, sdf), TimePickerUtil.parseData(endTime, sdf), TimePickerUtil.type2, true, body = {
                    slimAdapterEx.getDataItem(7).content = sdf.format(it)
                    slimAdapterEx.notifyItemChanged(7)
                    upload("activeStartTime" to sdf.format(it))
                })
            }
            8 -> {
                val startTime = slimAdapterEx.getDataItem(7).content
                val endTime = slimAdapterEx.getDataItem(8).content
                timePicker(TimePickerUtil.parseData(startTime, sdf), TimePickerUtil.parseData(endTime, sdf), TimePickerUtil.type2, false, body = {
                    slimAdapterEx.getDataItem(8).content = sdf.format(it)
                    slimAdapterEx.notifyItemChanged(8)
                    upload("activeEndTime" to sdf.format(it))
                })
            }
            6 -> {
                areaSelect { province, city, district ->
                    ChooseAlertView.getEditDiglog("请输入详细地址", "详细地址", null) { contents ->
                        slimAdapterEx.getDataItem(6).content = province + city + district + contents[0]
                        slimAdapterEx.getDataItem(6).tag = "$province,$city,$district${contents[0]}"
                        slimAdapterEx.notifyItemChanged(6)
                        upload("activeProvince" to province, "activeCity" to city, "activeAddress" to district + contents[0])

                    }.show(supportFragmentManager, "areaDialog")
                }
            }
        }


    }

    override fun setView() {
        tv_qiandao.onClick {
            startActivity<ActSignListActivity>(Config.ID to id)
        }

        tv_sign.onClick {
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.ACTIVITY_SIGN_IN)
                    .params("userGuid", user.guid)
                    .params("activityId", id)
                    .params("username", user.username)
                    .params("phone", user.uname)
                    .execute(object : DialogCallBack<HttpResult<*>>(this@ActDetailActivity) {
                        override fun onSuccess(response: Response<HttpResult<*>>?) {
                            response?.body()?.msg?.let {
                                toast(it)
                            }
                        }
                    })
        }
    }

    fun upload(vararg para: Pair<String, String?>) {
        val param = StringBuilder()

        para.forEach {
            param.append("${it.first}='${it.second}'").append(",")
        }

        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.ACTIVITY_UPDATE)
                .params("userGuid", user.guid)
                .params("activityId", id)
                .params("para", param.substring(0, param.length - 1))
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        response?.body()?.msg?.let {
                            toast(it)
                        }
                    }
                })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.INTENT_CONTENT) {
            val content = data?.getStringExtra("content")
            dataList.get(requestCode).content = content
            slimAdapterEx?.notifyItemChanged(requestCode)
            when (requestCode) {
                0 -> upload("activeTitle" to content)
                3 -> upload("activeObject" to content)
                4 -> upload("activeNum" to content)
                5 -> upload("activeScale" to content)
                13 -> upload("price" to content, "isCharge" to true.toString())
            }
        }

        if (resultCode == Config.SUCCESS) {
            when (requestCode) {
                10 -> {
                    val writeBean = data?.getSerializableExtra(Config.BEAN) as WriteBean?
                    slimAdapterEx?.getDataItem(10)?.content = writeBean?.html
                    slimAdapterEx?.getDataItem(10)?.tag = writeBean?.html
                    slimAdapterEx?.notifyItemChanged(10)
                    upload("activeDesc" to writeBean?.html)
                }
                11 -> {
                    val writeBean = data?.getSerializableExtra(Config.BEAN) as WriteBean?
                    slimAdapterEx?.getDataItem(11)?.content = writeBean?.html
                    slimAdapterEx?.getDataItem(11)?.tag = writeBean?.html
                    slimAdapterEx?.notifyItemChanged(11)
                    upload("activeSchedule" to writeBean?.html)
                }
            }
        }

        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val localMedias = PictureSelector.obtainMultipleResult(data)
                    ImageUtil.setImage(localMedias?.get(0)?.compressPath, iv_add)
                    val filePath = localMedias?.get(0)?.compressPath
                    HttpUtil.upLoadPic(this@ActDetailActivity, filePath) {
                        slimAdapterEx?.getDataItem(10)?.tag = it
                        upload("activeImg" to it.substring(HttpConfig.BASE_URL_NO.length, it.length))
                    }


                }
                2 -> {
                    val name = data?.getStringExtra(Config.NAME)
                    slimAdapterEx?.getDataItem(2)?.content = name
                    slimAdapterEx?.notifyItemChanged(2)
                    upload("activeClassify" to name)
                }
            }
        }


    }


    data class ActBean(
            val Id: Int,
            val activeType: String,// "大会",
            val activeClassify: String,//客户管理-客户服务管理",
            val activeTitle: String,//客户管理理论与实践",
            val activeNum: Int,// 100,
            val activeScale: String,//百人大会",
            val activeStartTime: String,//2018-09-01",
            val activeEndTime: String,//2019-09-01",
            val activeProvince: String,//河南省",
            val activeCity: String,//郑州市",
            val activeAddress: String,//金水区",
            val activeObject: String,//企业管理者",
            val activeImg: String,//https://www.eqid.top:8009/image/20180406/upload/18040611075972941.png",
            val activeDesc: String,//活动描述",
            val activeSchedule: String,//活动日程",
            val isCharge: Boolean,//false,
            val price: String,// 0,
            val name: String,//闫浩杰",
            val creater: String,//6c4448883b74401494907fab4de6596a",
            val createTime: String,//2018-09-19 11:46:58",
            val pageView: String,// 3,
            val regCount: String,// 1,
            val companyId: String// 46
    )
}